#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <unistd.h>

#include "config.h"
#include "epoll.h"

Ep *ep_create (int len)
{
    Ep *ep;
    int fd;
    struct epoll_event *ev;

    ep = (Ep *)malloc (sizeof(Ep));
    if (ep == NULL)
        return NULL;
    fd = epoll_create (len+1);
    if (fd < 0)
        return NULL;
    ev = (struct epoll_event *)malloc (sizeof(struct epoll_event)*len);
    if (ev == NULL)
        return NULL;

    ep->events = ev;
    ep->len = len;
    ep->fd = fd;
    ep->timeout = EPOLLTIMEOUT;

    return ep;
}

void ep_close (Ep *ep)
{
    if (ep == NULL)
        return;
    close (ep->fd);
    free (ep->events);
    free (ep);
}

int ep_add (Ep *ep, int sock, uint32_t events)
{
    struct epoll_event ev;

    ev.data.fd = sock;
    ev.events = events;

    return epoll_ctl (ep->fd, EPOLL_CTL_ADD, sock, &ev);
}

int ep_mod (Ep *ep, int sock, uint32_t events)
{
    struct epoll_event ev;

    ev.data.fd = sock;
    ev.events = events;

    return epoll_ctl (ep->fd, EPOLL_CTL_MOD, sock, &ev);
}

int ep_wait (Ep *ep)
{
    return epoll_wait (ep->fd, ep->events, ep->len, ep->timeout);
}
